<template>
  <div class="warpper">

    <div class="form" id="cadd">
      <el-form ref="ruleForm" :model="formData" :rules="rules" size="mini" label-width="168px" style="width:95%"
        :disabled="isdiable">

        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="Order Number" prop="ordernumber" style="width:460px">
              <el-input v-model="formData.ordernumber" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="Title" prop="title" style="width:460px">
              <el-input v-model="formData.title" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="Currency" prop="currency" style="width: 460px;">
              <el-select v-model="formData.currency" placeholder="Select Currency" style="width:290px;">
                <el-option v-for="item in currency" :key="item.id" :label="item.name" :value="item.name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="Rate" prop="rate" style="width: 460px;">
              <el-input v-model="formData.rate"></el-input>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="Symbol" prop="symbol" style="width: 458px;">
              <el-input v-model="formData.symbol"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="Description" prop="description" style="width: 460px;">
              <el-input v-model="formData.description"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="Start Date" prop="startdate" style="width:460px">
              <el-date-picker v-model="formData.startdate" type="datetime" style="width:290px"
                value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="End Date" prop="enddate" style="width:460px">
              <el-date-picker v-model="formData.enddate" type="datetime" style="width:290px"
                value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>


      </el-form>
      <div slot="footer" class="dialog-footer" style="margin-left: 170px;">
        <el-button plain type="default" @click="close()">Back</el-button>
        <el-button type="primary" @click="saveHandle('ruleForm')" :disabled="isdiable || isubmit">Submit</el-button>
      </div>
    </div>


  </div>
</template>

<script>
  import CURD from "@/mixin/CURD";
  import {
    index,
    show,
    update,
    store
  } from "@/api/quotationtemplate";
  import {
    index as warehouselist
  } from "@/api/warehouse";
  import {
    index as skushow
  } from "@/api/suppersku";
  import {
    index as prolist
  } from "@/api/product";
  import {
    index as customerindex
  } from "@/api/customer";
  import {
    store as uploadImg
  } from "@/api/medias";
  import {
    index as superindex
  } from "@/api/supplier";
  export default {
    name: "quotationtemplateadd",
    mixins: [CURD],
    data() {
      return {
        hoveredIndex: null,
        isubmit: false,
        rowIndex: 0,
        x: 0,
        y: 0,
        topx: '60%',
        isgoprolist: false,
        isdiable: false,
        staff: [{
          id: "LiLei",
          name: "LiLei",
        }, {
          id: "Haimei",
          name: "Haimei",
        }, {
          id: "Jack ma",
          name: "Jack ma",
        }],
        currency: [{
          id: 1,
          name: "SGD",
        }, {
          id: 2,
          name: "USD",
        }],
        term: [{
          id: 1,
          name: "SOB",
        }, {
          id: 2,
          name: "CIF",
        }],
        validityday: [{
          id: 30,
          name: 30,
        }, {
          id: 14,
          name: 14,
        }, {
          id: 60,
          name: 60,
        }],
        id: null,
        isEdit: false,
        isNew: false,
        formData: {
          staff: "LiLei",
          currency: "SGD",
          term: "SOB",
          validityday: 30,
          title: "",
          rate: "",
          symbol: "",
          description: "",
          startdate: "",
          enddate: "",
          procureditem: [],
        },
        module: "quotationtemplate",
        newTitle: "New quotationtemplate",
        editTitle: "Edit quotationtemplate",
        isPaginate: true,
        isUploadFile: false,
        fileReader: new FileReader(),
        isShow: false,
        imageUrl: "",
        suppliers: [],
        warehouse: [],
        xiabiao: -1,
        tindex: 0,
        tableData: [],
        customers: [],
        searchForm: {

        },
        isapproved: false,
        inputElements: [],
        tableDatav: [{
          id: "approved",
          name: "approved",
        }],
      };
    },
    mounted() {

    },
    watch: {
      'formData.procureditem': {
        handler() {
          //this.updateInputElements();
        },
        deep: true
      }
    },
    computed: {

    },
    async created() {
      this.id = this.$route.query.id
      if (this.id > 0) {
        this.isEdit = true
        const {
          data
        } = await show(this.id);
        this.formData = data;
        this.$forceUpdate();
      } else {
        var numStr = "01";
        const {
          data
        } = await index(1, 1);
        var lslist = data;
        if (data.length > 0) {
          var dqskinid = lslist[0].id + 1
          numStr = dqskinid.toString();
        }
        this.isNew = true
        this.isdiable = false
        const currentDate = new Date();
        const year = currentDate.getFullYear();
        const month = currentDate.getMonth() + 1;
        const day = currentDate.getDate();
        console.log(`${year}-${month}-${day}`);
        this.formData.addtime = `${year}-${month}-${day}`
        this.formData.ordernumber = "QT" + `${year}`.slice(-2) + "-" + numStr.padStart(4, '0')
        this.addItem()
        this.$nextTick(() => {
          const inputElement = document.querySelector(`.el-table__row input:nth-child(${1})`);
          if (inputElement) {
            if (inputElement) {
              const inputRect = inputElement.getBoundingClientRect();
              this.y = inputRect.left
              this.x = inputRect.top - 50
              console.log('Input coordinates:', this.x, this.y);
            }
          }
        });
      }
    },
    methods: {
      showButton(index) {
        if (isdiable || isapproved) {
          return
        }
        this.hoveredIndex = index; // 设置当前鼠标悬停的行的索引
      },
      hideButton(index) {
        if (isdiable) {
          return
        }
        if (this.hoveredIndex === index) {
          this.hoveredIndex = null; // 清除当前鼠标悬停的行的索引
        }
        // 注意：这里其实不需要传入 index，因为 mouseleave 事件已经足够判断鼠标离开了当前元素
        // 但为了保持与 showButton 方法参数的一致性，这里还是传入了 index（尽管未使用）
      },
      delcart(index) {
        this.formData.procureditem[index].certificates = null
      },
      getUploadHandler(index) {
        // 返回一个函数，该函数将作为 http-request 的处理器
        return (options) => {
          // 在这里，我们可以安全地使用 index，因为它是在这个闭包中捕获的
          this.rowIndex = index; // 如果需要在 uploadHandle 中使用，可以临时存储到组件的 data 或 properties 中
          this.uploadHandle(options);
        };
      },
      async uploadHandle(options) {
        const file = options.file;
        if (file) {
          this.fileReader.readAsDataURL(file);
        }
        this.fileReader.onload = () => {
          const formData = new FormData();
          formData.append("file", file);
          uploadImg(formData)
            .then((res) => {
              console.log(res)
              var {
                data
              } = res;
              this.$message.success(res.status);
              this.formData.procureditem[this.rowIndex].certificates = data.url
            })
            .catch((err) => {
              if (err.response.status === 422) {
                const {
                  info,
                  fileName
                } = err.response.data;
                this.$message.error(info);
              }
            });
        };

      },
      close() {
        this.$router.push({
          path: '/quotationtemplatelist/quotationtemplatelist'
        });
      },
      godisable() {
        this.isdiable = !this.isdiable
      },
      addItem() { //增加行
        this.xiabiao += 1
        this.formData.procureditem.push({
          index: this.xiabiao,
          productname: "",
          sku: "",
          unitweight: "",
          unitprice: "",
          minimumorder: "",
          note: "",
          product_id: ""
        });
      },
      removeItem(row) {
        const index = this.formData.procureditem.indexOf(row)
        if (this.formData.procureditem.length > 1) {
          this.formData.procureditem.splice(index, 1);
        } else {
          this.$message.error("Keep at least one row of data!")
        }
      },
      async editstatus(id, statusdata) {
        console.log(id)
        try {
          await this.$confirm("This operation will permanently Save status. Do you want to continue?", "prompt", {
            confirmButtonText: "Confirm",
            cancelButtonText: "Cancel",
            type: "warning"
          });
          let {
            info
          } = await update({
            id: id,
            action: "status",
            status: statusdata
          });
          this.$message.success("Status update successful");
          this.isapproved = true
        } catch (error) {
          this.$message({
            type: "info",
            message: "Cancelled save"
          });
        }
      },
      selectadd(row) {
        if (row) {
          // skushow(1, 1, {
          //   product_id: row.id
          // }).then(res => {
          //   if (res.data) {
          //     this.formData.procureditem[this.tindex].suppliesku = res.data[0].csku
          //     // this.formData.procureditem[this.tindex].costprice = res.data[0].price
          //   }
          // });
          this.formData.procureditem[this.tindex].productname = row.name
          this.formData.procureditem[this.tindex].sku = row.sku
          this.formData.procureditem[this.tindex].unitprice = row.price
          this.formData.procureditem[this.tindex].product_id = row.id
          this.isgoprolist = false;
        }
      },
      onChangeproductname(proname, index, event) {
        this.$nextTick(() => {
          this.topx = this.x + "px";
          console.log('Input coordinates:', this.x, this.y);
        });
        if (proname) {
          this.tindex = index
          prolist(1, 10000, {
            name: proname
          }).then(res => {
            this.tableData = res.data
            this.isgoprolist = true;
          });
        }
      },
      checkDataAndGetPosition(inputElement) {
        if (inputElement.value === '') {
          setTimeout(() => {
            this.checkDataAndGetPosition(inputElement);
          }, 1000); // 等待1秒后再次尝试获取数据
        } else {
          const inputRect = inputElement.getBoundingClientRect();
          const inputCoordinates = {
            x: inputRect.left,
            y: inputRect.top
          };
          console.log('Input coordinates:', inputCoordinates);
        }
      },
      handleClick(tab, event) {
        console.log(tab, event);
      },
      edit(id) {
        this.$router.push({
          path: '/product/editproduct',
          query: {
            id: id
          }
        })
      },
      onOpen(id) { // 展开
        this.currentOpen = id;
      },
      onClose(id) { // 关闭
        if (this.currentOpen === id) {
          this.currentOpen = null;
        }
      },
      async saveOrder(row) {
        let data = {
          id: row.id,
          order: row.order,
          action: "order"
        };
        row.isEdit = false;
        let {
          info
        } = await update(data);
        this.fetchData();
      },
      transfromData(data) {
        let result = data.map((item) => {
          item.isEdit = false;
          return item;
        });
        return result;
      },
      saveHandle(form) {
        this.save(form);
      },
      async save(form) {
        this.$refs[form].validate(async (valid) => {
          if (valid) {
            try {
              this.isubmit = true
              if (this.isEdit) {
                let {
                  update
                } = require(`@/api/${this.module}`);
                let {
                  info
                } = await update(this.formData);
                this.$message.success("Edit successfully");
                setTimeout(() => {
                  this.$store.dispatch('tagsView/delView', this.$route);
                  this.$router.push({
                    path: '/quotationtemplatelist/quotationtemplatelist'
                  });
                }, 1000);
              }
              if (this.isNew) {
                let {
                  store
                } = require(`@/api/${this.module}`);
                let info1 = await store(this.formData);
                this.$message.success("Add successfully");
                setTimeout(() => {
                  this.$store.dispatch('tagsView/delView', this.$route);
                  this.$router.push({
                    path: '/quotationtemplatelist/quotationtemplatelist'
                  });
                }, 1000);

              }
              this.fetchData();
              this.isEdit = false;
              this.isNew = false;
              this.isubmit = false
              this.dialogFormVisible = false;
            } catch (error) {
              let result = error.response.data;
              this.$message.error(result.info);
            }
          } else {
            this.isubmit = false
            this.$message.error("Data verification error, please input according to the specified rules");
            return false;
          }
        });
      },
      async avatarUpload(options) {
        const file = options.file;
        if (file) {
          this.fileReader.readAsDataURL(file);
        }
        this.fileReader.onload = async () => {
          const formData = new FormData();
          formData.append("file", file);
          uploadImg(formData)
            .then((res) => {
              const {
                data
              } = res;
              this.formData.image = data.url;
              //this.save("ruleForm");
            })
            .catch((err) => {
              options.onError(err);
            });
        };
      },
      changeAvatar(file, fileList) {
        console.log("sssssssssssssssssss")
        const reader = new window.FileReader();
        reader.readAsDataURL(new Blob([file.raw]));
        reader.onload = (e) => {
          this.formData.image = reader.result;
          this.imageUrl = reader.result;
          this.isUploadFile = true;
          console.log(reader.result)
        };
      },
      async changeStatus(row) {
        let tips = "";
        if (row.status) {
          tips = "是否启用该文章?";
        } else {
          tips = "是否禁用该文章?";
        }
        this.$confirm(tips, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(async () => {
            let data = {
              id: row.id,
              status: row.status,
              action: "status"
            };
            let {
              info
            } = await update(data);
            this.$message.success(info);
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "Cancelled deletion"
            });
          });
      }

    }
  }
</script>
<style>
  .avatar-uploader {
    position: relative;
  }

  .customWidth {
    width: 80%;
  }

  .tableDatav .has-gutter {
    display: none;
  }

  .cadd {
    width: 100%;
  }

  .plt {
    position: absolute;
    z-index: 9999;
    left: 170px;
    background: #fff;
  }

  #cadd .el-table th.el-table__cell>.cell {
    display: inline-block;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    position: relative;
    vertical-align: middle;
    padding-left: 10px;
    padding-right: 10px;
    width: 100%;
    font-weight: 600 !important;
    color: #000;
    font-size: 14px !important;
  }
</style>
<style>
  .warpper {
    padding: 30px 20px;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
  }

  .table,
  .toolbar,
  .page {
    margin: 20px;
  }

  .toolbar {
    margin-top: 10px;
    padding: 5px;
  }

  .table {
    margin-bottom: 10px;
  }

  .page {
    margin-top: 10px;
    text-align: center;
  }

  .green-text {
    color: green;
  }

  .red-text {
    color: red;
  }

  .yellow-text {
    color: yellow;
  }
</style>